package com.network.retrofit_rx.Api;

import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * @author QiQi
 * @ClassName: MyResponseBodyConverterFactory
 * @date 2018/6/11
 * @copyrights 浙江维融电子有限公司
 */
public class BooleanConverterFactory extends Converter.Factory {

    public static BooleanConverterFactory create() {
        return new BooleanConverterFactory();
    }


    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        if (Boolean.class.equals(type)) {
            return new BooleanConverter();
        }
        return super.responseBodyConverter(type, annotations, retrofit);
    }


    private static class BooleanConverter implements Converter<ResponseBody, Boolean> {
        @Override
        public Boolean convert(@NonNull ResponseBody value) throws IOException {
            JSONObject jsonObject = JSONObject.parseObject(value.string());
            String result = jsonObject.getString("code");
            if ("200".equals(result)) {
                return true;
            } else {
                throw new RuntimeException(jsonObject.getString("msg"));
            }
        }
    }
}
